import React, { Component, Fragment } from 'react';
import { connect } from 'react-redux'
class SetState extends Component {
    constructor(props) {
        super(props);
        this.state = {
            counter: 0
        }
        this.synBtn = React.createRef();
        this.asynBtn = React.createRef();
    }
    componentDidMount() {
        console.dir(this.synBtn);
        console.dir(this.asynBtn);
        this.synBtn.addEventListener('click', () => {
            console.log('同步counter值:', this.state.counter);
            this.setState({ counter: this.state.counter + 1 });
            console.log('同步改变操作后counter值:', this.state.counter);
        })
    }
    // synClick = () => {
    //     this.setState({ counter: this.counter + 1 });
    //     console.log('同步改变counter:', this.state.counter);
    // }
    asynClick = () => {
        console.log('异步counter值:', this.state.counter);
        this.setState({
            counter: this.state.counter + 1
        },()=>{
            console.log('异步改变操作后回调counter值:', this.state.counter);
        });
        console.log('异步改变操作后counter值:', this.state.counter);
    }
    render() {
        return (
            <Fragment>
                在原生事件中调用this.setState,此时setState是同步的
                <br/>
                <button ref={c => this.synBtn = c}>onclick 原生事件</button>
                <br />
                在合成事件种调用this.setState,此时setState是异步的
                <br/>
                <button ref={c => this.asynBtn = c} onClick={this.asynClick}>onClick 合成事件</button>
            </Fragment>
        )
    }

}

export default connect()(SetState);